/*
 * Copyright (C) 2012, EADS France
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */
package xowl.gmi.environment;

/**
 *
 * @author Laurent WOUTERS
 */
public class ProjectExecution {
    private MainController main;
    private xowl.gmi.model.ExecutionEntry entry;
    private xowl.lang.runtime.Value[] params;
    private ProjectController project;
    private xowl.gmi.view.WinOutput.Document output;
    private xowl.interpreter.Thread thread;
    
    public ProjectExecution(MainController main, xowl.gmi.model.ExecutionEntry entry, xowl.lang.runtime.Value[] params) {
        this.main = main;
        this.entry = entry;
        this.params = params;
    }
    
    public void run() {
        main.getView().makeOutputVisible();
        output = main.getView().getWinOutput().newDocument(entry.getName());
        
        project = new ProjectController(main, xowl.gmi.model.DiagramNode.generateID("onto"));
        xowl.lang.runtime.Value function = main.getRepository().resolveEntity(entry.getFunctionIRI());
        try {
            output.writeLine("Executing: " + entry.getFunctionIRI(), java.awt.Color.GRAY);
            thread = xowl.interpreter.Interpreter.createThread(main.getRepository());
            thread.addHooks(main.getHooks());
            thread.setRuntimeOntology(project.getOntology());
            main.registerExecution(thread, this);
            xowl.lang.runtime.Value value = thread.run(function, params);
            main.unregisterExecution(thread);
            output.writeLine("Returned: " + xowl.utils.Values.toString(value), java.awt.Color.GRAY);
        } catch (xowl.interpreter.XOWLException ex) {
            if (thread != null)
                main.unregisterExecution(thread);
            output.writeLine("Execution threw an exception: " + ex.getHeadline(), java.awt.Color.RED);
            for (java.lang.StackTraceElement elem : ex.getStackTrace())
                output.writeLine("\t" + elem.toString(), java.awt.Color.RED);
        }
    }
    
    public void print(String message) { output.writeLine(message); }
    
    public String getOntology() { return project.getOntology().getHasIRI().getHasValue(); }
    
    public void createDiagram(xowl.lang.runtime.Entity model, String viewID, String name) {
        xowl.gmi.model.WorkbenchView wbv = main.getWorkbench().getView(viewID);
        DiagramController dc = project.addDiagram(name, wbv, model.getHasIRI().getHasValue());
    }
}
